package com.wl.cloud.security.component;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.URLUtil;
import com.wl.cloud.security.bean.IgnoreUrlsProperties;
import com.wl.cloud.security.constant.SecurityConstants;
import com.wl.cloud.security.enums.SecurityErrorCode;
import com.wl.cloud.security.service.DynamicSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author: wanglin
 * @date: 2023-09-12 周二
 * @Version: 1.0
 * @Description: 动态权限数据源，用于获取动态权限规则
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;
    @Autowired
    private IgnoreUrlsProperties ignoreUrlsProperties;


    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        if (configAttributeMap == null) {
            this.loadDataSource();
        }
        List<ConfigAttribute> configAttributes = new ArrayList<>();

        //获取当前用户角色
        List<GrantedAuthority> authorities = (List<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        boolean isAdminFlag = authorities.stream().map(e -> e.getAuthority()).anyMatch(x -> SecurityConstants.ADMIN.equals(x) || SecurityConstants.SUPER_ADMIN.equals(x));
        //若是管理员，则直接放行
        if (isAdminFlag) {
            return configAttributes;
        }

        String url = ((FilterInvocation) o).getRequestUrl();
        String path = URLUtil.getPath(url);
        PathMatcher pathMatcher = new AntPathMatcher();

        //不需要操作权限的接口
        List<String> apiList = ignoreUrlsProperties.getApis();
        boolean apiFlag = apiList.stream().anyMatch(e -> pathMatcher.match(e, path));
        if (apiFlag) {
            return configAttributes;
        }

        //获取当前访问的路径
        Iterator<String> iterator = configAttributeMap.keySet().iterator();
        //获取访问该路径所需资源
        while (iterator.hasNext()) {
            String pattern = iterator.next();
            if (pathMatcher.match(pattern, path)) {
                //可能一个URL路径对应多个角色，如:test1,COMMON
                String[] roles = configAttributeMap.get(pattern).getAttribute().split(",");
                for (String role : roles) {
                    configAttributes.add(new SecurityConfig(role));
                }
            }
        }
        // 未设置操作请求权限，返回空集合
        if (CollUtil.isEmpty(configAttributes)) {
            throw new AccessDeniedException(SecurityErrorCode.UNAUTHORIZED.getDescription());
        }
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
